using System;
using UnityEngine;

namespace Voodoo.Sauce.Internal
{
	public static class VoodooLog
	{
		private const string TAG = "VoodooSauce";

		public const string LOG_LEVEL_PLAYER_PREFS_KEY = "VoodooLogLevel2";

		public const string FILTER_PLAYER_PREFS_KEY = "VoodooLogFilter";

		private static ILogger _logger;

		public static bool IsDebugLogsEnabled => _logger.LogLevel == LogType.Log;

		internal static LogType GetLogLevel => _logger.LogLevel;

		internal static int ModuleFilter => _logger.ModuleFilter;

		public static event Action<string, string, LogType> logReceived
		{
			add
			{
				_logger.logReceived += value;
			}
			remove
			{
				_logger.logReceived -= value;
			}
		}

		static VoodooLog()
		{
			Debug.unityLogger.logEnabled = true;
			_logger = new VoodooLogger();
			_logger.ModuleFilter = Math.Min(NintendoPlayerPrefs.GetInt("VoodooLogFilter", 255), 255);
			LogType fall = ((Application.isEditor || Debug.isDebugBuild) ? LogType.Log : LogType.Error);
			SetLogLevel((LogType)NintendoPlayerPrefs.GetInt("VoodooLogLevel2", (int)fall));
		}

		public static void LogDebug(Module module, string tag, string message)
		{
			Log(module, tag, message, LogType.Log);
		}

		public static void LogError(Module module, string tag, string message)
		{
			Log(module, tag, message, LogType.Error);
		}

		public static void LogWarning(Module module, string tag, string message)
		{
			Log(module, tag, message, LogType.Warning);
		}

		private static void Log(Module module, string tag, string message, LogType logType)
		{
			_logger.Log(Format(module, tag, message), module, logType);
		}

		private static string Format(Module module, string tag, string message)
		{
			return string.Format("{0}/{1}/{2}: {3}", "VoodooSauce", module, tag, message);
		}

		public static void EnableDebugLogs(bool enable)
		{
			SetLogLevel(enable ? 3 : 0);
		}

		internal static void SetLogLevel(LogType logType)
		{
			SetLogLevel((int)logType);
		}

		internal static void SetLogLevel(int value)
		{
			_logger.LogLevel = (LogType)value;
			Debug.unityLogger.filterLogType = _logger.LogLevel;
			NintendoPlayerPrefs.SetInt("VoodooLogLevel2", value);
			UpdateAnalyticsLogLevel();
		}

		internal static void ToggleModule(int value)
		{
			_logger.ModuleFilter = value ^ _logger.ModuleFilter;
			NintendoPlayerPrefs.SetInt("VoodooLogFilter", _logger.ModuleFilter);
			UpdateAnalyticsLogLevel();
		}

		private static void UpdateAnalyticsLogLevel()
		{
			if (IsDebugLogsEnabled)
			{
				_ = (ModuleFilter & 2) > 0;
			}
			else
				_ = 0;
		}
	}
}
